package com.thm.tfast.core.sevruity.component;

import com.thm.tfast.core.enums.PermissionEnum;
import com.thm.tfast.modules.sys.model.vo.resource.ResourceVo;
import com.thm.tfast.modules.sys.service.SysResourceService;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author THM
 * @date 2022/10/24
 * @desc
 */
@Order(1)
@Component
public class DynamicSecurityService {
    @Resource
    private SysResourceService sysResourceService;

    public Map<String, Map<String,ConfigAttribute>> loadDataSource() {
        Map<String,Map<String, ConfigAttribute>> resultMap = new ConcurrentHashMap<>();
        List<ResourceVo> resourceList = sysResourceService.getAllResource();
        Map<String, List<ResourceVo>> resourceMap = resourceList.stream().collect(Collectors.groupingBy(ResourceVo::getPrefix));
        Iterator<Map.Entry<String, List<ResourceVo>>> iterator = resourceMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, List<ResourceVo>> next = iterator.next();
            List<ResourceVo> value = next.getValue();

            Map<String, ConfigAttribute> map = new ConcurrentHashMap<>();;
            value.forEach(sysResource -> {
                if (Objects.equals(PermissionEnum.HAS.getCode(), sysResource.getHasPermission()))
                    map.put(sysResource.getUrl(), new SecurityConfig(sysResource.getPermission()));
            });
            resultMap.put(next.getKey(),map);
        }
        return resultMap;
    }
}
